<!DOCTYPE html>
<html>
  <head>
    <title>四十五度游戏地图编辑器</title>
    <meta charset="utf-8">
  </head>
  <style>
  </style>
  <body style="background-color:#ccc;">
	<script type="text/javascript" src="../libs/minicomps.min.js"></script>
	<script type="text/javascript" src="../libs/FileSaver.js"></script>
	<script type="text/javascript" src="../libs/easeljs.js"></script>
	<script type="text/javascript" src="../libs/Unify.js"></script>
	<script>		
	const { Toggle, HSlider,VSlider,Panel, Canvas ,Button,TextArea,TextBox,TextInput,Label,Window,Image,LabelInput,TipsManager,RadioButton,ColorPicker,TabbarWindow,Checkbox,Knob,Stage,MoonTextArea,Dropdown} = mc
	const width = Stage.width-20;
	const height = Stage.height-20;
	const panel = new Panel(document.body, 0, 0, width,height);
	const canvas=new Canvas(panel, 0, 20,width-5,height-20);
	const stage=new createjs.Stage(canvas);
	createjs.Ticker.addEventListener("tick",(e)=>{
		stage.update();
	});
	Window.draggable = false;
    Window.minimizable = false;
	const colors=['#FF0000','#ffbb00','#fa5500','#BB3300','#666600','#660000','#333399','#006666','#006633','#003300','#0033ff'];
	var GameCount=0;//格子数据数量
	var isAddTable=true;//是增加单位格子/否是删除单位格子
	var isDragImage=false;//是否可以拖动图片
	var tables=[];//用二维数组存单位格子
	var items=[];//用一维数组存单位格子
	var tableXNum=12;//表格x轴的个数
	var tableYNum=12;//表格y轴的个数
	var boxW=100;//格子宽
	var boxH=50;//格子高
	var mapx=100;//x轴偏移数值
	var mapy=350;//y轴偏移数值

	canvas.setOverflowAuto();
	let btnNames=['创建地图','删除数据','导出数据','增加格子','删除格子','删除图片','修改尺寸','修改图片比例'];
	for(let i=0;i<btnNames.length;i++){
		let name=btnNames[i];
		let btn=new Button(panel,i*100,0,name,onClick);
		btn.name=name;
	}
	Toggle.labelPosition = "left";
	HSlider.labelPosition = "left";
	var imgToggle=new Toggle(panel, (btnNames.length+1)*100, 0, '图片拖动开关', isDragImage,(e)=>{isDragImage=!isDragImage;tipLabel.text='';});
	new HSlider(panel, imgToggle.x+150, 2, '改变图片大小', 50, 0, 100, (e)=>{if(this.bitmap){let v=e.detail/50;this.bitmap.scaleX=v;this.bitmap.scaleY=v;}})
	var tipLabel=new createjs.Text('hello',"20px Arial", "#ff0000");
	tipLabel.x=width*0.5;
	tipLabel.y=5;
	tipLabel.textAlign='center';
	stage.addChild(tipLabel);
	//顶部按钮事件
	function onClick(e){
		let btn=e.target;
		let index=btnNames.indexOf(btn.name);
		//console.log(index);
		switch(index){
			case 0:
				createTable();
				break;
			case 1:
				removeData();
				break;
			case 2:
				saveData();
				break;
			case 3:
				tipLabel.text='当前状态可以增加单位格子或编辑单位格子'
				isAddTable=true;
				break;
			case 4:
				tipLabel.text='当前状态是删除单位格子'
				isAddTable=false;
				break;
			case 5:
				removeImage();
				break;
			case 6:
				changeTable();
				break;
			case 7:
				changeImage();
				break;
		}
	}
	//创建表格
	function createTable(){
		let win=new Window(document.body,0,0,300,300,'创建表格数据');
		win.x=(width-win.width)>>1;
		win.y=(height-win.height)>>1;
		let labels=['x轴数量','y轴数量','单位格子宽','单位格子高','x轴偏移数值','y轴偏移数值'];
		let values=[tableXNum,tableYNum,boxW,boxH,mapx,mapy];
		let inputs=[];
		for(let i=0;i<labels.length;i++){
			let label=new LabelInput(win,10,10+i*30,labels[i]);
			label.input.text=values[i];
			inputs.push(label.input);
		}
		new Button(win,100,200,'创建',()=>{
			let datas=[];
			inputs.forEach((input)=>{datas.push(parseInt(input.text))});
			createData(datas);
			win.removeFromParent();
		});
	}
	//修改表格
	function changeTable(){
		let win=new Window(document.body,0,0,300,300,'修改表格数据');
		win.x=(width-win.width)>>1;
		win.y=(height-win.height)>>1;
		let labels=['单位格子宽','单位格子高','x轴偏移数值','y轴偏移数值'];
		let values=[52,35,300,300];
		let inputs=[];
		for(let i=0;i<labels.length;i++){
			let label=new LabelInput(win,10,10+i*30,labels[i]);
			label.input.text=values[i];
			inputs.push(label.input);
		}
		new Button(win,100,200,'修改',()=>{
			boxW=Number(inputs[0].text);
			boxH=Number(inputs[1].text);
			mapx=Number(inputs[2].text);
			mapy=Number(inputs[3].text);
			if(this.orgData){
				let o=this.orgData['1']
				let s=String(o['YX']).split('-');
				let tableYNum=Number(s[0]);
				let tableXNum=Number(s[1]);
				let datas=[tableXNum,tableYNum];
				inputs.forEach((input)=>{datas.push(parseInt(input.text))});
				createData(datas);
				drawData();
			}
			win.removeFromParent();
			TipsManager.alert('修改成功');
		});
	}
	//删除数据
	function removeData(){
		TipsManager.SureCancel('确定要删除数据吗？',(e)=>{
			if(e.detail){
				GameCount=0;
				if(this.items){
					this.items.forEach((item)=>{
						item.remove();
					})
				}
			}
		})
	}
	//删除所有数据
	function removeAllData(){
		GameCount=0;
		stage.removeAllChildren();
		stage.addChild(tipLabel);
	}
	//创建数据
	function createData(datas){
		removeAllData();
		//console.log(datas);
		let [tableXNum,tableYNum,boxW,boxH,mapx,mapy]=datas;
		var pw=tableYNum*boxW;
		var ph=tableYNum*boxH;
		//var id=0;
		var mx=mapx!=0?mapx:pw/2;
		var my=mapy!=0?mapy:ph/2;
		tables=[];
		items=[];				
		for(let i=0;i<tableYNum;i++){
			var array=[];
			for(let j=0;j<tableXNum;j++){
				let item=new BoxItem(boxW,boxH);
				item.name="x"+j+",y"+i;
				//item.data['id']=++id;
				item.data['pos']=j+'-'+i;
				item.data['YX']=tableYNum+'-'+tableXNum;
				item.addEventListener("click",onItemClick);
				//item.addEventListener(Event.CHANGE,onChange);
				item.x+=item.width/2*i+item.width/2*j+mx;
				item.y+=item.height/2*i-item.height/2*j+my;
				stage.addChild(item);
				this.items.push(item);
				array.push(item);
			}
			tables.push(array);
		}
		if(pw>width)canvas.width=pw+boxW;
		if(ph>height)canvas.height=ph+boxH;
	}
	//单击单位格子
	function onItemClick(e){
		if(isDragImage){
			tipLabel.text='请关闭图片拖动开关'
			return;
		}
		let item=e.currentTarget;
		//console.log(item)
		//console.log(item.data);
		if(isAddTable){
			if(!item.hasMap){
				item.add();
			}else{
				if(this.dataWindow==null){
					this.dataWindow=new DataWindow(document.body,0,0);
				}else{
					this.dataWindow.addFromParent();
				}
				this.dataWindow.setData(item);
			}
		}else{
			if(item.hasMap){
				item.remove();
			}
		}
	}
	//删除图片
	function removeImage(){
		if(this.bitmap){
			stage.removeChild(this.bitmap);
			this.bitmap=null;
			isDragImage=false;
			imgToggle.toggled=isDragImage;
		}
	}
	//加载图片
	function loadImage(url){
		tipLabel.text='图片可自由拖动'
		this.removeImage();
		isDragImage=true;
		imgToggle.toggled=isDragImage;
		var bitmap = new createjs.Bitmap(url);
		stage.addChildAt(bitmap,0);
		this.bitmap=bitmap;
		stage.removeEventListener("stagemousedown",doMouseDown);
		stage.addEventListener("stagemousedown", doMouseDown);
		function doMouseDown(e){
			if(!isDragImage)return;
			let [x,y,maxX,maxY]=[e.stageX,e.stageY,bitmap.x+bitmap.image.naturalWidth,bitmap.y+bitmap.image.naturalHeight];
			if(bitmap.x<x&&x<maxX&&bitmap.y<y&&y<maxY){
				stage.addEventListener('stagemousemove', doMouseMove,false);
				stage.addEventListener('stagemouseup',  doMouseUp, false);
				bitmap.startX=x-bitmap.x;
				bitmap.startY=y-bitmap.y;
			}
		}
		function doMouseMove(e){
			let [x,y]=[e.stageX,e.stageY];
            x-=bitmap.startX;
			y-=bitmap.startY;
			bitmap.x=x;
			bitmap.y=y;
		}
		function doMouseUp(e){
			stage.removeEventListener('stagemousemove', doMouseMove,false);
			stage.removeEventListener('stagemouseup',  doMouseUp, false);
		}
	}
	function changeImage(){
		let win=new Window(document.body,0,0,300,300,'修改图片比例');
		win.x=(width-win.width)>>1;
		win.y=(height-win.height)>>1;
		let labels=['图片比例'];
		let values=[0.5];
		let inputs=[];
		for(let i=0;i<labels.length;i++){
			let label=new LabelInput(win,10,10+i*30,labels[i]);
			label.input.text=values[i];
			inputs.push(label.input);
		}
		new Button(win,100,200,'修改',()=>{
			let v=Number(inputs[0].text);
			if(this.bitmap){
				this.bitmap.scaleX=v;this.bitmap.scaleY=v;
				TipsManager.alert('修改成功');
			}
			win.removeFromParent();
		});
	}
	//加载JSON数据
	function loadJson(data){
		var o=data['1'];
		var s=String(o['YX']).split('-')
		tableYNum=Number(s[0]);
		tableXNum=Number(s[1]);
		let datas=[tableXNum,tableYNum,boxW,boxH,mapx,mapy];
		createData(datas);
		//console.log(tables)
		this.orgData=data;
		drawData();
		GameCount=count;
		isAddTable=true;
	}
	function drawData(){
		let data=this.orgData;
		var count=0;
		for (let i in data){
			o=data[i];
			s=String(o['pos']).split('-');
			//console.log(s);
			var item=tables[s[1]][s[0]];
			item.setData(o);
			count++;
		}
	}
	/**数据保存到本地*/
	function saveData(e){
		var value="{"
		items.forEach((item)=>{
			if(item.hasMap){
				var o=item.data;
				var v='"'+o["id"]+'":'+JSON.stringify(o)+',';
				value+=v;
			}
		});
		value=value.substr(0,value.length-1);
		value+="}";
		//console.log(value);
		var file = new File([value], "data.json");
		saveAs(file);
	}
	class BoxItem extends createjs.Container{
		constructor(w,h){
			super();
			this.data={};
			this.width=w;
			this.height=h;
			this.shape=new createjs.Shape();
			this.colorBg="rgba(255,255,0,0.1)";
			this.colorMap="rgba(255,0,0,1)";
			this.drawBox(this.colorBg);
			this.addChild(this.shape);
			this.label=new createjs.Text('',"15px Arial", "#ffffff");
			this.label.x=w*0.5;
			this.label.y=-7;
			this.label.textAlign='center';
			this.addChild(this.label);
		}
		drawBox(color){
			let[w,h]=[this.width,this.height];
			this.shape.graphics.clear();
			this.shape.graphics.setStrokeStyle(1);
			this.shape.graphics.beginStroke("black");
			this.shape.graphics.beginFill(color).moveTo(0,0).lineTo(w/2,-h/2).lineTo(w,0).lineTo(w/2,h/2).lineTo(0,0)//.lineTo(0,-h);
		}
		setData(data){
			this.hasMap=true;
			this.data=data;
			this.update();
		}
		add(){
			if(this.hasMap)return;
			GameCount++;
			this.drawBox(this.colorMap);
			this.label.text=''+GameCount;
			this.hasMap=true;
			this.data['id']=GameCount;
			this.data['event']=0;
			this.data['param']=0;
			this.data['icon']=-1;
		}
		update(){
			let data=this.data;
			this.label.text=data['id'];
			var i=data.event>=colors.length?colors.length-1:data.event;
			if(isNaN(i)) i=colors.length-1;
			var color=colors[i];//连接点是黑色
			this.drawBox(color);
		}
		remove(){
			if(this.hasMap){
				this.hasMap=false;
				this.drawBox(this.colorBg);
				this.label.text='';
				delete this.data['id'];
				delete this.data['event'];
				delete this.data['param'];
				delete this.data['icon'];
				GameCount--;
				if(GameCount<0)GameCount=0;
			}
		}
	}
	class DataWindow extends Window{
		constructor(parent, xpos, ypos)
		{
			super(parent, xpos, ypos);
			let w=200;
			this.setSize(w,w);
			this.x=(width-w)/2;
			this.y=(height-w)/2;
			this.createText();
		}
		createText(){
			var names=['id','事件','参数','图片'];
			var h=30;
			var win=this;
			for(var i=0;i<names.length;i++){
				new Label(this,0,i*h,names[i]);
				switch(i){
					case 0:
						this.txtId=new TextInput(win,50,i*h);
						this.txtId.setSize(100,26);
						break;
					case 1:
						this.txtEvent=new TextInput(win,50,i*h);
						this.txtEvent.setSize(100,26);
						break;
					case 2:
						this.txtParam=new TextInput(win,50,i*h);
						this.txtParam.setSize(100,26);
						break;
					case 3:
						this.txtIcon=new TextInput(win,50,i*h);
						this.txtIcon.setSize(100,26);
						break;
				}
			}
		}
		setData(item){
			this.item=item;
			this.txtId.text=this.item.data.id;
			this.txtEvent.text=this.item.data.event;
			this.txtParam.text=this.item.data.param;
			this.txtIcon.text=this.item.data.icon;
		}
		removeFromParent()
		{
			this.item.data.id=this.txtId.text;
			this.item.data.event=this.txtEvent.text;
			this.item.data.param=this.txtParam.text;
			this.item.data.icon=this.txtIcon.text;
			this.item.update();
			super.removeFromParent();
		}
	}
	customElements.define("minimal-window99", DataWindow);

	//---------加载数据处理-------------
	
	var box = document.createElement('div');
	box.innerText='导入数据时可直接拖入此处'
	box.style='position:absolute;left:1.5%;top:5%;height:24px;width:200px;background-color:#444444;color:#ffffff;'
	document.body.appendChild(box);
	box.ondragover = function (e) {
		e.preventDefault();
	}
	box.ondrop = function (e) {
		e.preventDefault();
		var f = e.dataTransfer.files[0];//获取到第一个上传的文件对象
		var fr = new FileReader();//实例FileReader对象
		fr.readAsDataURL(f);//把上传的文件对象转换成url
		fr.onload = function (e) {
			var url=e.target.result;//上传文件的URL
			//console.log(e);
			if(url.indexOf('data:image/')===0){
				console.log('加载图片')
				loadImage(url);
			}else if(url.indexOf('data:application/json')===0){
				//console.log('加载json')
				var request=new XMLHttpRequest();
				request.open('get',url);
				request.send(null);
				request.onload=function(){
					if(request.status==200){
						var json=JSON.parse(request.responseText);
						loadJson(json);
					}
				}
			}
		}
	}
	</script>
  </body>
</html>
